package cn.kgm.comsumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 消费消息
 * Create by kappi on
 * 2021/8/24/024 13:45
 */
public class Consumer {
    public static void main(String[] args) throws InterruptedException, MQClientException {

        // Instantiate with specified consumer group name.
        // 使用指定的用户组名进行实例化
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("kagim" );

        // Specify name server addresses.
        // 指定名称服务器地址
        consumer.setNamesrvAddr("localhost:9876" );

        // Subscribe one more more topics to consume.
        // 再订阅一个主题以供使用。
        consumer.subscribe("kagimTopic", "*" );
        // Register callback to execute on arrival of messages fetched from brokers.
        // 注册要在从代理获取的消息到达时执行的回调。
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                if (!CollectionUtils.isEmpty(msgs)) {
                    for (MessageExt msg : msgs) {
                        System.out.println(new String(msg.getBody()));
                    }
                }
                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // Launch the consumer instance.
        // 启动消费者实例。
        consumer.start();
        // 消费者不需要关闭，要一直等待消息消费
        System.out.printf("Consumer Started.%n" );
    }
}
